package com.free.framework.lib.network;

import com.free.framework.BuildConfig;
import com.free.framework.lib.utils.ContextHolder;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author 李博
 * @date 16/8/14
 */
public class Retrofit2Mgr {

    private static final int CONN_TIME_OUT = 30;
    private static final int READ_TIME_OUT = 30;
    private static final int CACHE_SIZE = 10 * 1024 * 1024;

    private static volatile Retrofit2Mgr mRtf2Mgr;

    private Retrofit.Builder mRtfBuilder;

    private static HashMap<String, Retrofit> mRtfContainer;

    private Retrofit2Mgr() {

        Gson gson = new GsonBuilder().create();
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
                .connectTimeout(CONN_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
                .sslSocketFactory(SSLSocketFactoryGen.genSSLSocketFactory())
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .retryOnConnectionFailure(true)
                .cache(new Cache(ContextHolder.getContext().getCacheDir(), CACHE_SIZE))
                .addInterceptor(CommonHeaderInterceptor.getInstance());
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(new HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT)
                    .setLevel(HttpLoggingInterceptor.Level.BODY));
        }

        mRtfBuilder = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create());

        mRtfContainer = new HashMap<>();
    }

    public static Retrofit2Mgr getInstance() {

        if (mRtf2Mgr == null) {
            synchronized (Retrofit2Mgr.class) {
                if (mRtf2Mgr == null) {
                    mRtf2Mgr = new Retrofit2Mgr();
                }
            }
        }

        return mRtf2Mgr;
    }

    /**
     * @param baseUrl
     * @return
     * @desc 根据baseUrl生成Retrofit实例
     */
    public Retrofit getRetrofit(String baseUrl) {

        Retrofit retrofit = mRtfContainer.get(baseUrl);
        if (null == retrofit) {
            retrofit = mRtfBuilder.baseUrl(baseUrl).build();
            mRtfContainer.put(baseUrl, retrofit);
        }
        return retrofit;
    }

}
